/*
 * @Author: zhousg
 * @Date: 2020-10-30 16:24:54
 * @Last Modified by: zhousg
 * @Last Modified time: 2020-11-11 14:51:30
 */

let startEvent
let id = 0
const nodeList = []
const ATTR = '@clickoutsidecontext@'
document.addEventListener('mousedown', e => {
  startEvent = e
})
document.addEventListener('mouseup', e => {
  nodeList.forEach(el => {
    if (!startEvent.target ||
      !e.target ||
      el.contains(startEvent.target) ||
      el.contains(e.target) ||
      el === e.target) {
      return
    }
    el[ATTR].fn && el[ATTR].fn()
  })
})
export default {
  bind (el, binding) {
    id++
    el[ATTR] = { id, fn: binding.value }
    nodeList.push(el)
  },
  unbind (el) {
    const index = nodeList.findIndex(node => node[ATTR].id === el[ATTR].id)
    nodeList.splice(index, 1)
    delete el[ATTR]
  }
}
